/*
Copyright 2008  Four Roads LLC conact@4-roads.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either 
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with this library.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommunityServer.Components;
using CommunityServer.Controls;
using CA = Telligent.Web.UI;
using ResourceManager = FourRoads.Links.Controls.ResourceManager;

namespace FourRoads.Links.Controls
{
	public class CommentMainModeration : TemplatedWebControl
	{
		public CommentMainModeration(): base()
		{
			this.SkinName = "Skin-ClientPopulatedPopupMenu.ascx";
		}

		protected CA.PopupMenu menu;

		
		#region Skin

		protected override void AttachChildControls() 
		{
            menu = (CA.PopupMenu)FindControl("Menu");
		}

		#endregion

		#region Control Event Handlers

		protected override void OnLoad(EventArgs e)
		{
			this.EnsureChildControls();

			menu.Visible = false;

			if (this.Context.Items["ClientPopulatedPopupMenu_" + this.SkinName + "_Menu"] == null)
			{
				this.Context.Items.Add("ClientPopulatedPopupMenu_" + this.SkinName + "_Menu", menu);
				menu.Visible = true;
			}
			else
                menu = (CA.PopupMenu)this.Context.Items["ClientPopulatedPopupMenu_" + this.SkinName + "_Menu"];

			base.OnLoad(e);
		}

		protected override void OnPreRender(EventArgs e)
		{
			if (!this.Page.IsClientScriptBlockRegistered("CommunityServer.Controls.ClientPopulatedPopupMenu"))
				this.Page.RegisterClientScriptBlock("CommunityServer.Controls.ClientPopulatedPopupMenu", string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>",this.ResolveUrl("~/utility/ClientPopulatedPopupMenu.js")));

			if (!this.Page.IsStartupScriptRegistered(this.ClientID))
			{
				StringBuilder sb = new StringBuilder();
				sb.Append("[");
				foreach (ClientMenuItemFormat format in this.ClientMenuItemFormats)
				{
                    if (sb.Length > 1)
                        sb.Append(",");

                    sb.Append("[");

                    sb.Append(format.ClientSideDisplayFunction);
                    sb.Append(",");
                    sb.Append(FormatJavaScript(format.Text, true));
                    sb.Append(",");
                    sb.Append(FormatJavaScript(format.Icon, true));
                    sb.Append(",");
                    sb.Append(FormatJavaScript(format.NavigateUrl, true));
                    sb.Append(",");
                    sb.Append(FormatJavaScript(format.Target, true));
                    sb.Append(",");
                    sb.Append(FormatJavaScript(format.ClientSideCommand, true));


                    sb.Append("]");
				}
				sb.Append("]");

				Page.RegisterStartupScript(this.ClientID, String.Format("<script language=\"javascript\">window.{0} = new ClientPopulatedPopupMenu('{0}','{1}','{2}','{3}',{4});</script>", this.ClientID, this.menu.ClientID, this.InactiveButtonCssClass, this.ActiveButtonCssClass, sb.ToString()));
			}

			base.OnPreRender(e);
		}

		#endregion

		#region Helper Methods

		protected string FormatJavaScript(string value, bool wrapInQuotes)
		{
			if (Globals.IsNullorEmpty(value))
			{
				return "null";
			}
			
			value = value.Replace("'", "\\'");

			if (wrapInQuotes)
				return "'" + value + "'";
			else
				return value;
		}

		protected ArrayList ClientMenuItemFormats
		{
			get
			{
				ArrayList formats = new ArrayList();
				ClientMenuItemFormat format;

				// 0 - CommentID, 1 - sectionID, 2 - IsApproved, 3 - Comment User ID, 4 - Comment User ModerationLevel 
				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return (parseInt(parms[3]) != 1 && parseInt(parms[4]) == 1);')";
				format.Text = ResourceManager.GetString("ResLinkModerationMenu_Approve");
				format.ClientSideCommand = "javascript:ajaxApproveComment({0},{1},{2},{7});";
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return (parseInt(parms[4]) == 1 && parseInt(parms[6]) != 1);')";
				format.Text = ResourceManager.GetString("ResLinkModerationMenu_Delete");
				format.NavigateUrl = ResLinkUrls.Instance().ModerateDeleteComment( 99999 , 99998 , 99997 , CSContext.Current.RawUrl).Replace("99999" , "{0}").Replace("99998" , "{1}").Replace("99997" , "{2}");
				formats.Add(format);
		
				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parseInt(parms[6]) == 1;')";
				format.Text = ResourceManager.GetString("ResLinkModerationMenu_Delete");
				format.ClientSideCommand = "javascript:ajaxDeleteComment({0},{1},{2},{7});";
				formats.Add(format); 


				return formats;
			}
		}

		protected string MenuParameterJavaScript
		{
			get
			{
				object state = this.ViewState["MenuParameterJavaScript"];
				if (state == null)
					return "null";
				else
					return (string) state;
			}
			set
			{
				ViewState["MenuParameterJavaScript"] = value;
			}
		}

		public override string ClientID
		{
			get
			{
				EnsureChildControls();
				return this.menu.ClientID + "_" + this.GetType().Name;
			}
		}
		#endregion
		/// <summary>
		/// Property UsePathToRedirect (bool)
		/// </summary>
		public bool UsePathToRedirect
		{
			get 
			{  
				object obj = ViewState["UsePathToRedirect"];
				return obj == null ? false : (bool)obj;
			}
			set {  ViewState["UsePathToRedirect"] = value; }
		}

		protected string Text
		{
			get
			{
				string state = (string) this.ViewState["Text"];
				if (state == null)
					return "";
				else
					return state;
			}
			set
			{
				this.ViewState["Text"] = value;
			}
		}

		public virtual string InactiveButtonCssClass
		{
			get
			{
				string state = (string) this.ViewState["InactiveButtonCssClass"];
				if (state == null)
					return "";
				else
					return state;
			}
			set
			{
				this.ViewState["InactiveButtonCssClass"] = value;
			}
		}

		public virtual string ActiveButtonCssClass
		{
			get
			{
				string state = (string) this.ViewState["ActiveButtonCssClass"];
				if (state == null)
					return "";
				else
					return state;
			}
			set
			{
				this.ViewState["ActiveButtonCssClass"] = value;
			}
		}

		public void CreateAjaxJavascript()
		{
			StringBuilder sb = new StringBuilder(500);

			sb.Append("\n<script language='javascript' type=\"text/javascript\">\n");
			sb.AppendFormat("\nfunction ajaxDeleteComment(sectionID , postID , commentID  , callbackFunc)\n{{\nCommentMainModeration.DeleteComment('{0}', sectionID , postID , commentID , callbackFunc);\n}}\n" , ClientID);
		//	sb.Append("function ajaxDeleteCommentResponse(result){alert(result);}");
		
			sb.AppendFormat("\nfunction ajaxApproveComment(sectionID , postID , commentID  , callbackFunc)\n{{\nCommentMainModeration.ApproveComment('{0}', sectionID , postID , commentID , callbackFunc);\n}}\n" , ClientID);
	//		sb.Append("function ajaxApproveCommentResponse(result){alert(result);}");

			sb.Append("\n</script>");

			Page.RegisterClientScriptBlock(ClientID + "AjaxMenus", sb.ToString());

		}

		protected override void OnInit(EventArgs e) 
		{						
			AjaxManager.Register(this , "CommentMainModeration" , true , AjaxDebug.None );
			CreateAjaxJavascript();
			base.OnInit(e);
		}

		///Two ajax methods for handling comments
		[AjaxMethod(IncludeControlValuesWithCallBack = false)]
		public string DeleteComment(int sectionID , int postID , int commentID)
		{
			ResLinkLink lnk = ResLinkLink.GetSingleLink(postID);

			lnk.DeleteComment(sectionID , commentID);

			return string.Format("{0}^{1}^{2}" ,sectionID , postID , commentID);
		}

		[AjaxMethod(IncludeControlValuesWithCallBack = false)]
		public string ApproveComment(int sectionID ,int postID , int commentID)
		{
			ResLinkLink lnk = ResLinkLink.GetSingleLink(postID);

			foreach(ResLinkComments cmt in lnk.Comments)
			{
				if (cmt.PostID == commentID)
				{
					lnk.ApproveComment(cmt);
					break;
				}
			}

			return string.Format("{0}^{1}^{2}" , sectionID , postID , commentID);
		}
	}

	// *********************************************************************
	//  ModerationMenu
	//
	/// <summary>
	/// This control renders a moderation menu used by forum moderators
	/// to moderate new posts.
	/// </summary>
	// ********************************************************************/ 	
	public class CommentModeration : ClientPopulatedPopupMenu
	{
		protected override void OnLoad(EventArgs e) 
		{
			base.OnLoad(e);
		}
	
		CSContext csContext;
		bool canModerate = false;
		bool isOwner = false;

		protected override void OnInit(EventArgs e) 
		{
			csContext = CSContext.Current;
			this.ResourceName = "ModerationPopupMenu_Text";

			base.OnInit(e);
		}

		protected override ArrayList ClientMenuItemFormats
		{
			get
			{
				ArrayList formats = new ArrayList();
				ClientMenuItemFormat format;

				// 0 - CommentID, 1 - sectionID, 2 - IsApproved, 3 - Comment User ID, 4 - Comment User ModerationLevel 
				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return (parseInt(parms[3]) != 1 && parseInt(parms[4]) == 1);')";
				format.Text = ResourceManager.GetString("ResLinkModerationMenu_Approve");
				format.ClientSideCommand = "javascript:ajaxApproveComment({0},{1},{2},{7});";
				formats.Add(format);

				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return (parseInt(parms[4]) == 1 && parseInt(parms[6]) != 1);')";
				format.Text = ResourceManager.GetString("ResLinkModerationMenu_Delete");
				format.NavigateUrl = ResLinkUrls.Instance().ModerateDeleteComment( int.MaxValue , int.MaxValue-1 , int.MaxValue-2 , ResLinkUrls.Instance().ViewLink(Section.SectionID  , Comment.ParentID)).Replace(int.MaxValue.ToString() , "{0}").Replace((int.MaxValue-1).ToString() , "{1}").Replace((int.MaxValue-2).ToString() , "{2}");
				formats.Add(format);
		
				format = new ClientMenuItemFormat();
				format.ClientSideDisplayFunction = "new Function('parms', 'return parseInt(parms[6]) == 1;')";
				format.Text = ResourceManager.GetString("ResLinkModerationMenu_Delete");
				format.ClientSideCommand = "javascript:ajaxDeleteComment({0},{1},{2},{7});";
				formats.Add(format); 

				return formats;
			}
		}
	
		protected override void Render(HtmlTextWriter writer)
		{
			Visible = (UserHasAccess);

			if (Visible)
			{
				if (Parameters.Length != 8)
				{
					this.Parameters = new string[8];
					this.Parameters[0] = this.Comment.SectionID.ToString();
					this.Parameters[1] = this.Comment.ParentID.ToString();
					this.Parameters[2] = this.Comment.PostID.ToString();
					this.Parameters[3] = this.Comment.IsApproved ? "1" : "0";
					this.Parameters[4] = canModerate ? "1" : "0";
					this.Parameters[5] = this.Comment.User.ModerationLevel.ToString();
					this.Parameters[6] = isOwner ? "1" : "0";
					this.Parameters[7] = CallbackClientID;
				}
				
				base.Render (writer);
			}
		}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
		}

		public string CallbackClientID
		{
			get
			{
				return (string)ViewState["CallbackClientID"];
			}
			set
			{
				ViewState["CallbackClientID"] = value;
			}
		}

		private ResLinkLink post = null;
		public ResLinkLink Post 
		{
			get 
			{
				return post;
			}
			set 
			{
				post = value;
			}
		}

		private ResLinkComments comment = null;
		public ResLinkComments Comment 
		{
			get 
			{
				return comment;
			}
			set 
			{
				comment = value;
			}
		}

		private ResLinkSection section = null;
		public ResLinkSection Section 
		{
			get 
			{
				return section;
			}
			set 
			{
				section = value;
			}
		}


		public bool UserHasAccess
		{
			get
			{
				if (ViewState["UserHasAccess"] == null)
				{
					if (Section != null)
					{
						isOwner = CSContext.Current.User.UserID == Comment.UserID;
						canModerate = Permissions.ValidatePermissions(Section, (Permission)ResLinkPermissionEnum.Moderate , csContext.User);
						canModerate |= ExtendedUserRoles.IsLinkAdministrator || CSContext.Current.User.IsModerator;

						ViewState["UserHasAccess"] = (canModerate || isOwner);
					}
					else
					{
						ViewState["UserHasAccess"] = false;
					}
				}
				return (bool)ViewState["UserHasAccess"];
			}
		}

		public override string ClientID
		{
			get
			{
				EnsureChildControls();
				return this.menu.ClientID + "_CommentMainModeration";
			}
		}
	}
}

